<template>
    <div class="Main">
        <top/>
        <div class="content">
            <div class="find">
                <div class="form">
                    <input type="text" v-model="key" placeholder="输入任意关键字"/>
                    <button @click="search()">搜索</button>
                </div>
            </div>
            <div class="result">
                <div class="left">
                    <p>限定检索结果</p>
                    <div class="form2">
                        <div class="input" v-for="item in  limit" :key="item.key">
                            <label v-text="item.name"/>
                            <input type="text" v-model="item.val"/>
                        </div>
                        <button @click="search()" class="t-btn">确定</button>
                    </div>
                    <p v-show="order.length > 0" class="p2">待下单图书</p>
                    <div v-show="order.length > 0" class="form2">
                        <ol>
                            <li v-for="(item,index) in order" :key="index"
                                :title="item.book_name"
                            >
                                {{item.book_name.length > 14 ? item.book_name.substr(0,14) + '...' :item.book_name}}
                                <span title="移除" @click="order.splice(order.indexOf(item),1)">一</span>
                            </li>
                        </ol>
                        <button @click="makeOrder()" class="t-btn">确认订单</button>
                        <br/>
                        <label>收货地址</label>
                        <select class="t-input" v-model="curAddress">
                            <option v-for="(item,index) in address"
                                    :key="index"
                                    v-text="item.name + '-'+ item.address"
                                    :value="item"/>
                        </select>
                    </div>
                </div>
                <div class="right">
                    <p>搜索结果</p>
                    <table>
                        <thead>
                        <tr>
                            <th v-for="(word,key) in cols" :key="key" v-text="word"/>
                            <th>下单</th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr v-for="(item,index) in rows" :key="index">
                            <td v-for="key in Object.keys(cols)" :key="key"
                                v-text="item[key].length > 12 ? item[key].substr(0,12) + '...' : item[key]"
                                :title="item[key]"/>
                            <td class="add-btn" @click="add(item)"/>
                        </tr>
                        </tbody>
                        <tfoot>
                        <tr>
                            <td :colspan="Object.keys(cols).length + 1">
                                <button @click="next(page - 1)" :disabled="page === 1">上一页</button>
                                <label>{{page}}/{{totalPage}}</label>
                                <button @click="next(page + 1)" :disabled="page === totalPage">下一页</button>
                            </td>
                        </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
        <bottom/>
    </div>
</template>

<script>
    import axios from "axios";

    export default {
        props: {},
        data() {
            return {
                // 搜索关键字
                key: '',
                // 限定检索条件
                limit: [{name: '作者', key: 'author', val: ''},
                    {name: '标题', key: 'title', val: ''},
                    {name: '索取号', key: 'callno_f', val: ''}],
                // 搜索结果table
                cols: {book_name: '书名', book_editor: '作者', book_publish: '出版社', book_index: '索引号', num: '可借'},
                rows: [],
                // 当前页数
                page: 1,
                // 总页数
                totalPage: 1,
                // 每页的数量
                singlePage: 10,

                // 待下单的清单
                order: [],

                // 地址列表
                address: [],

                // 当前地址
                curAddress: {}
            }
        },
        created() {
            // 检查是否在登录状态
            this.$axios.get('/user')
                .then(res => {
                    if (res.data.code !== 200) {
                        // 清除全局用户信息
                        this.$store.commit('clearUser');
                    } else {
                        // 调用自定义方法
                        if (this.$vals.role === 'teacher')
                            // 初始化地址
                            this.getAddress();
                    }
                });
            // 初始化列表
            this.search();
        },
        methods: {
            // 获取地址
            getAddress() {
                this.$axios.get('/address').then(res => {
                    if (res.data.code === 200) {
                        this.address = res.data.content;
                        if (this.address.length > 0)
                            this.curAddress = this.address[0];
                    } else {
                        window.alert('地址列表初始化异常，请刷新再试');
                    }
                });
            },

            // 下单
            makeOrder() {
                if (this.curAddress.name === undefined) {
                    window.alert('请选择收货地址');
                    return;
                }
                if (!window.confirm("确认下单吗？\n收件人："
                    + this.curAddress.name + "\n收货电话：" + this.curAddress.tel
                    + "\n详细地址：" + this.curAddress.address)) {
                    return;
                }
                window.console.log(this.curAddress, this.order);
                // 下单操作
                this.$axios.post('/order', {
                    data: JSON.stringify({
                        id: this.curAddress.id,
                        books: this.order
                    })
                }).then(this.$then);
                this.curAddress = {};
            },

            // 添加到待下单的目录
            add(item) {
                if (this.$vals.username === '') {
                    alert('请先登录！');
                    return;
                }
                if (item.num <= 0) {
                    alert('该图书已经被借完了！');
                    return;
                }
                if (!(this.order.includes(item)))
                    this.order.push(item);
            },
            getWhere() {
                // 查询的where条件
                let res = {};
                // 添加任意关键字
                res.anywords = this.key === '' ? 'c' : this.key;
                // 普通特定关键字
                for (let item of this.limit) {
                    if (item.val === '')
                        continue;
                    res[item.key] = item.val;
                }
                // 每页的数量
                res.dp = this.singlePage;
                // 当前页
                res.page = this.page;
                window.console.log(res);
                return res;
            },

            // 搜索
            search() {
                this.$axios.get('/order/book', {params: this.getWhere()})
                    .then(res => {
                        if (res.data.code === 200) {
                            let content = res.data.content;
                            this.page = parseInt(content.page);
                            this.totalPage = parseInt(content.totalPage);
                            this.rows = content.rows;
                        } else if (res.data.code === 400) {
                            window.alert(res.data.content);
                        }
                    })
            },
            // 换页
            next(val) {
                if (val <= 0 || val > this.totalPage)
                    return;
                this.page = val;
                this.search();
            },
        }
    };
</script>
<style scoped lang="scss">
    @import "Main";
</style>
